package com.kuangqiyuan.yatzygame.rule;

import com.kuangqiyuan.yatzygame.Play;

import java.util.Arrays;

/**
 * 处理一下几种规则
 * - 两个两个相同
 * - 三张相同加一对
 */
public class TwoPairesRuleHandler extends AbstractRuleHandler {
  private class PairRecord {
    private int number;
    private int count;
    private int score;

    public PairRecord(int number, int count) {
      this.number = number;
      this.count = count;
      this.score = this.number * this.count;
    }

    public void setNumber(int number) {
      this.number = number;
    }

    public void setCount(int count) {
      this.count = count;
    }

    public int getScore() {
      return this.score;
    }
  }

  public TwoPairesRuleHandler() {
    super();
  }

  @Override
  public int Count() {
    int[] board = new int[6];
    for (int i = 0; i < board.length; i++) {
      board[i] = 0;
    }

    for (int i = 0, m; i < 5; i++) {
      m = this.play.getRecord(i);
      board[m - 1]++;
    }

    int maxPairCount = (int)Math.floor(5 / 2);  // 最多不超过两对
    PairRecord[] pairs = new PairRecord[maxPairCount];
    int[] scores = new int[maxPairCount];
    int countCursor = 0;
    for (int i = 0; i < board.length; i++) {
      // 有相同的牌（2、3、4、5 张相同的牌）
      if (board[i] > 1) {
        PairRecord thisPair = new PairRecord(i + 1, board[i]);
        int index = pairs.length;

        pairs[countCursor] = thisPair;
        scores[countCursor] = thisPair.getScore();
        countCursor++;
      }
    }

    // 没有两种以上的对牌（筛选出 4、5 张相同牌的情况）
    if (countCursor < 1) {
      return 0;
    }

    Arrays.sort(scores);
    int topScore = scores[scores.length - 1] + scores[scores.length - 2];

//    System.out.println(String.format("%s counts: %d", this.getClass(), topScore));

    return topScore;
  }
}
